package com.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bean.User;
import com.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
	@Autowired
	private UserService userService;

	@RequestMapping("index")
	public String index() {
		return "index";
	}

	@RequestMapping("login1")
	public String login1(@ModelAttribute("user") User user) {
		User tuser = userService.findByNameAndPw(user);
		if (tuser == null) {
			return "index";
		}
		return "list";
	}

	@RequestMapping("login2") // 等价reques.setAttribute("user",user)
	public String login2(User user, Model model) {
		User tuser = userService.findByNameAndPw(user);
		if (tuser == null) {
			return "index";
		}
		model.addAttribute("user", tuser);// 作用域是request请求
		return "list";
	}

	@RequestMapping("login3") // 等价reques.setAttribute("user",user)
	public String login3(User user, HttpServletRequest request) {
		User tuser = userService.findByNameAndPw(user);
		if (tuser == null) {
			return "index";
		}
		request.setAttribute("user", tuser);// 作用域是request请求
		return "list";
	}

	@RequestMapping("login4")
	public ModelAndView login4(User user) {
		ModelAndView mv = new ModelAndView();
		User tuser = userService.findByNameAndPw(user);
		if (tuser == null) {
			mv.setViewName("index");
		}
		mv.setViewName("redirect:/emp/list");
		mv.addObject("user", tuser);
		return mv;
	}

	@RequestMapping("login")
	public String login(User user, Model model) {
		User tuser = userService.findByNameAndPw(user);
		if (tuser == null) {
			return "index";
		}
		model.addAttribute("user", user);
		return "redirect:/emp/list";
	}

	@RequestMapping("toregister")
	public String toregister() {
		return "userAdd";
	}

	@RequestMapping("checkName")
	@ResponseBody
	public String checkName(String name) {
		User user = userService.checkName(name);
		String flag = "0";
		if (user == null) {
			flag = "0";
		} else {
			flag = "1";
		}
		return flag;
	}

	@RequestMapping("save")
	public String save(User user) {
		this.userService.save(user);
		return "index";
	}
}
